#ifndef DATABASE_H
#define DATABASE_H

#include <QObject>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDateTime>
#include <QStringList>
#include <QVariant>
#include <QFile>

class Database : public QObject
{
    Q_OBJECT
public:
    explicit Database(QObject *parent = nullptr);
    ~Database();

    bool openDatabase(const QString &dbPath = "");
    bool closeDatabase();
    bool exportDatabase(const QString &filePath);
    bool importDatabase(const QString &filePath);
    bool initializeDatabase();
    bool initializeDormitoryData();

    // 单元和房间管理
    QStringList getBuildingUnits();
    QStringList getRoomsByUnit(const QString &unit);
    bool addUnit(const QString &unitName);
    bool addRoom(const QString &unitName, const QString &roomNumber);
    bool deleteUnit(const QString &unitName);
    bool deleteRoom(const QString &unitName, const QString &roomNumber);
    bool updateRoom(const QString &unitName, const QString &oldRoom, const QString &newRoom);
    bool hasScoreRecords(const QString &unitName, const QString &roomNumber);
    bool deleteRelatedScoreRecords(const QString &unitName, const QString &roomNumber);

    // 评分记录管理
    struct ScoreRecord
    {
        int id;
        QString date;
        QString unit;
        QString room;
        QString score;  // "优", "良", "差"
        QString issues; // 多个问题用逗号分隔："消防,抽烟,卫生,安全"
    };

    QList<ScoreRecord> getScoresByDate(const QString &date);
    QList<ScoreRecord> getScoresByDateAndUnit(const QString &date, const QString &unit);
    bool saveScoreRecord(const QString &date, const QString &unit, const QString &room,
                         const QString &score, const QString &issues);
    bool hasScoreRecordForDate(const QString &date, const QString &unit, const QString &room);
    bool deleteScoreRecord(int recordId);
    bool deleteScoreRecordsByDate(const QString &date, const QString &unit, const QString &room);

    // 月度统计
    struct MonthlyStats
    {
        QString unit;
        QString room;
        int excellentCount;
        int goodCount;
        int poorCount;
        int fireIssueCount;
        int smokingIssueCount;
        int sanitaryIssueCount;
        int safetyIssueCount;
    };

    QList<MonthlyStats> getMonthlyStats(const QString &startDate, const QString &endDate);

private:
    QSqlDatabase db;
    bool createTables();
    bool validateSqliteFile(const QString &filePath);
};

#endif // DATABASE_H